﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Xml;

using Microsoft.Samples.Office.UnifiedCommunications.Gadget.Config;

namespace Microsoft.Samples.Office.UnifiedCommunications.Gadget.EWSUtility
{
    public class EWSConfiguration
    {
        public string ewsUrl { get; set; }  // Exchange Web Services Url
        public string umUrl { get; set; }   // Unified Messaging Url

        private const string EXCHANGE_PROTOCOL = "EXCH";
        private const string EWSURL_ELEMENT = "EwsUrl";

        public EWSConfiguration() { }

        public void DiscoverEWSUrl(string user, string domain, string password, string email)
        {
            NetworkCredential nc = new NetworkCredential(user, password, domain);
            bool allowSelfSignedCerts = false;

            try
            {
                // Identifies the maximum number of redirections through either SCP pointer or Autodiscover redirects 
                int maxHops = 10;

                Autodiscover.AutodiscoverResponseXml response =
                    Autodiscover.Discover(email, nc, ref maxHops, allowSelfSignedCerts);

                if (response != null)
                {
                    if (response.OutlookData != null)
                    {
                        if (response.OutlookData.Account.Protocol != null)
                        {
                            foreach (Autodiscover.ProtocolXml protocolXml in response.OutlookData.Account.Protocol)
                            {
                                if (protocolXml.Type == EXCHANGE_PROTOCOL)
                                {
                                    umUrl = protocolXml.UMUrl;

                                    if (protocolXml.OtherXml != null)
                                    {
                                        foreach (object otherXml in protocolXml.OtherXml)
                                        {
                                            XmlLinkedNode ln = otherXml as XmlLinkedNode;
                                            if (ln.Name == EWSURL_ELEMENT)
                                            {
                                                ewsUrl = ln.InnerText;
                                                break;
                                            }
                                        }
                                    }
                                    break;
                                }
                            }
                        }
                    }

                    if ((response.ErrorResponse != null) && (response.ErrorResponse.Error != null))
                    {
                        Exception errorResponse = new Exception(string.Concat(
                            "ErrorCode: ", response.ErrorResponse.Error.ErrorCode, 
                            Environment.NewLine, "Message: ", response.ErrorResponse.Error.Message));
                        throw (errorResponse);
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        public void ManuallyConfigureEWS(string server, string user, string domain, string password)
        {
            string attemptUrl = "https://" + server + "/ews/Exchange.asmx";

            ewsUrl = attemptUrl;

            // TODO: Attempt to verify

            //HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(attemptUrl);
            //request.Method = "GET";
            //request.ContentType = "text/xml;utf-8";
            //request.Credentials = new NetworkCredential(user, password, domain);

            //HttpWebResponse response;
            //try
            //{
            //    response = request.GetResponse() as HttpWebResponse; // Try to get the response
            //    if (response != null) // assume success
            //        ewsUrl = attemptUrl;
            //}
            //catch (WebException webException)
            //{
            //    throw webException;
            //}
        }

        public static bool IsEWSConfigured()
        {
            SettingsEWS curSettings = GadgetConfigurationManager.GetUserSettingsEWS();
            if (!string.IsNullOrEmpty(curSettings.EWSUrl) || !string.IsNullOrEmpty(curSettings.ExchangeServer))
                return true;
            else
                return false;
        }
    }
}
